import { defineStore } from 'pinia'
import { authLogin, authLogout, infoUserProfile } from '@a/public'
import { getLightColor, getDarkColor } from '@/utils/theme/tool'
import router from '@/router'
import guarder from './guarder'

export default defineStore('user', {
	state: () => ({
		userInfo: {},
		menuTabsList: [],
		remark: '',
		token: '',
		uid: '',
		avatar: '',
		permissions: [],
		roles: [],
		ElIcons: [], // 字体图标数组
		svgIcons: [], // svg字体图标数组
		theme: {
			type: 'light',
			primaryColor: '#409eff',
			collapsible: true, //开启折叠
			showTabs: true, // 是否显示导航历史
			layout: 'sidebar', // 布局
			logo: true, // 显示logo
			menuType: 'science',
			showBreadcrumb: true // 开启面包屑
		},
		// 缓存选中菜单和tab，防止不在菜单中展示的页面刷新之后，无选中效果
		activeMenu: '',
		activeMenuTab: '',
		// 表格自定义表头
		columns: {},
		// 高级搜索自定义查询条件
		search: {}
	}),
	getters: {
		userIdGets: (state) => state.userInfo.userId,
		rolesGets: (state) => state.roles,
		permissionsGets: (state) => state.permissions,
		// 按照当前账号保存表格自定义表头
		GetColumns: (state) => (key) => state.columns[state.userInfo.userId]?.[key],
		// 按照当前账号保存高级搜索条件
		GetSearch: (state) => (key) => state.search[state.userInfo.userId]?.[key]
	},
	actions: {
		// 主题修改
		stateChange(data) {
			this.theme = data
			const body = document.documentElement
			body.setAttribute('id', this.theme.menuType)
			body.style.setProperty('--el-color-primary', this.theme.primaryColor)
			// 颜色
			for (let i = 1; i <= 9; i++) {
				body.style.setProperty(
					`--el-color-primary-light-${i}`,
					this.theme.type === 'light' ? `${getLightColor(this.theme.primaryColor, i / 10)}` : `${getDarkColor(this.theme.primaryColor, i / 10)}`
				)
			}
		},
		// 黑白主题切换
		stateChangeType(data) {
			this.stateChange(data)

			const vm = this,
				isLight = this.theme.type === 'light'

			function changeFn() {
				const body = document.documentElement
				// 设置全局顶部body上的class名称，即为主题名称，便于自定义配置符合当前主题的样式统一入口
				body.setAttribute('class', vm.theme.type)
			}

			// 浏览器不支持 View Transitions 时的回退方案：
			const e = document.querySelector('#themeSwitch')
			if (!document.startViewTransition || !e) {
				changeFn()
				return
			}

			// 开始一次视图过渡：
			const transition = document.startViewTransition(() => changeFn())
			transition.ready.then(() => {
				// 由于我们要从鼠标点击的位置开始做动画，所以我们需要先获取到鼠标的位置
				const { offsetLeft: clientX, offsetHeight: clientY } = e.parentElement

				// 计算半径，以鼠标点击的位置为圆心，到四个角的距离中最大的那个作为半径
				const radius = Math.hypot(Math.max(clientX, innerWidth - clientX), Math.max(clientY, innerHeight - clientY))

				const clipPath = [`circle(0% at ${clientX}px ${clientY}px)`, `circle(${radius}px at ${clientX}px ${clientY}px)`]

				// 自定义动画
				document.documentElement.animate(
					{
						clipPath: isLight ? clipPath : clipPath.reverse()
					},
					{
						duration: 500,
						easing: 'ease-in',
						// 如果要切换到暗色主题，我们应该裁剪 view-transition-old(root) 的内容
						pseudoElement: isLight ? '::view-transition-new(root)' : '::view-transition-old(root)'
					}
				)
			})
		},
		// 页面表格头部缓存
		SetColumns(key, val) {
			if (!this.columns[this.userInfo.userId]) this.columns[this.userInfo.userId] = {}
			this.columns[this.userInfo.userId][key] = val
		},
		// 按照当前账号保存高级搜索条件
		SetSearch(key, val) {
			if (!this.search[this.userInfo.userId]) this.search[this.userInfo.userId] = {}
			this.search[this.userInfo.userId][key] = val
		},
		// 登录
		Login(data) {
			return new Promise((resolve, reject) => {
				authLogin(data)
					.then((res) => {
						this.token = res?.data?.tk
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 获取用户信息
		GetInfo() {
			return new Promise((resolve, reject) => {
				infoUserProfile()
					.then((res) => {
						if (res?.data) {
							const { user, roles: Roles = ['ROLE_DEFAULT'], perms } = res?.data || {}

							// 验证返回的roles是否是一个非空数组
							this.roles = Roles
							// 按钮级权限数组
							this.permissions = perms
							// 用户信息
							this.userInfo = {
								userId: user.id,
								userName: user.userName,
								nickName: user.nickName,
								deptId: user.deptId
							}
							this.avatar = user.avatar
							this.remark = user.remark
						}
						resolve(res)
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 退出系统
		LogOut() {
			return new Promise((resolve, reject) => {
				authLogout()
					.then(() => {
						this.LogOutSET()
						resolve()
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		LogOutSET() {
			// 退出登录removeRoute删除动态添加的路由
			guarder().addRouter.forEach((item) => {
				router.removeRoute(item.name || item.path)
			})
			guarder().addRouter = []
			this.token = ''
			this.uid = ''
			this.roles = []
			this.permissions = []
			this.menuTabsList = []
			this.activeMenu = ''
			this.activeMenuTab = ''
			$store.guarder.Menus = []
		}
	},
	// 开启数据缓存
	persist: {
		enabled: true,
		strategies: [
			{
				key: 'user',
				storage: localStorage,
				paths: [
					'token',
					'roles',
					'permissions',
					'userInfo',
					'avatar',
					'remark',
					'menuTabsList',
					'theme',
					'activeMenu',
					'activeMenuTab',
					'columns',
					'search'
				]
			}
		]
	}
})
